import $ from 'jquery'
import store from '@/store'
import StaticStore from './StaticStore'
export default {
	/**
	 * @desc 首页
	 */
	state: {
		list: [],
		page: 1,
		hasNext: false,
		loadmoreText: "加载更多"
	},
	mutations: {
		/**
		 * @desc 保存数据
		 */
		updateList(state, data) {
			state.list = data
		},
		setLoadMoreText(state, data) {
			state.loadmoreText = data
		}
	},
	//处理mutations中的函数，区别是可以包含异步操作，使用this.$store.dispatch(actionName)调用
	actions: {
		/**
		 * @desc 请求数据
		 */
		getListData({
			commit,
			state
		}, categoryId) {
			state.loadmoreText = "正在加载..."
			let url = StaticStore.state.baseUrl + '/m/index.php?c=home&a=lists&json=1&page=' + state.page + '&id=' + categoryId
			$.ajax({
				url: url,
				dataType: 'jsonp',
				jsonp: 'callback',
				success: function(result) {
					var arr = state.list
					if(state.page == 1) {
						arr = []
					}
					arr.push.apply(arr, result)
					store.commit('updateList', arr)
					//console.log("get list data success", result)
					if(result.length >= 10) {
						state.hasNext = true
						state.loadmoreText = "加载更多"
					} else {
						state.loadmoreText = "已加载全部"
					}
				},
				error: function(error) {
					console.log(error)
				}
			});
		},
		refreshListData({
			commit,
			state
		}, categoryId) {
			//返回顶部
			document.body.scrollTop = 0
			document.documentElement.scrollTop = 0
			state.page = 1
			store.dispatch("getListData", categoryId)
		},
		loadListData({
			commit,
			state
		}, categoryId) {
			if(state.hasNext) {
				state.page++
				store.dispatch("getListData", categoryId)
				state.hasNext = false
			}
		}
	}
}